package com.learn.tomcat.server;

import com.learn.tomcat.processor.Processor;
import com.learn.tomcat.processor.SaticResourceProcessor;
import com.learn.tomcat.processor.ServletProcessor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * <li>http://localhost:8080/staticResource</li>
 * <li>http://localhost:8080/servlet/servletClass</li>
 * <li>http://localhost:8080/servlet/PrimitiveServlet</li>
 */
public class HttpServer {
    private static final String SHOTDOWN_COMMAND = "/SHOTDOWN";
    private boolean showdown = false;

    public static void main(String[] args) {
        HttpServer server = new HttpServer();
        server.await();
    }

    private void await() {
        ServerSocket serverSocket = null;
        int port = 8080;
        Socket socket = null;
        InputStream input = null;
        OutputStream output = null;
        try {
            serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
            System.out.println("new serverSocket " + serverSocket.getInetAddress().getHostAddress() + ":" + serverSocket.getLocalPort());
            while (!showdown) {
                System.out.println("serverSocket accept");
                socket = serverSocket.accept();
                input = socket.getInputStream();
                output = socket.getOutputStream();

                Request request = new Request(input);
                request.parse();

                Response response = new Response(output);
                response.setRequest(request);

                if (!request.getUri().equals(SHOTDOWN_COMMAND)) {
                    Processor processor;
                    if (request.getUri().startsWith("/servlet/")) {
                        processor = new ServletProcessor();
                    } else {
                        processor = new SaticResourceProcessor();
                    }
                    processor.process(request, response);
                } else {
                    response.sendSHOTDOWN();
                    showdown = true;
                }
            }
            System.out.println("serverSocket showdown seccess");
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        } finally {
            try {
                if (output != null) output.close();
                if (input != null) input.close();
                if (socket != null) socket.close();
                if (serverSocket != null) serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
